/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    typedef ListNode Node;
    void _merge(Node* head, Node* a, Node* b)
    {
        if (a == nullptr || b == nullptr)
        {
            head->next = a == nullptr ? b : a;
            return;
        }

        Node* aNext = a->next;
        Node* bNext = b->next;
        if (a->val > b->val)
        {
            head->next = b;
            head = b;

            _merge(head, a, bNext);
        }
        else
        {
            head->next = a;
            head = a;

            _merge(head, aNext, b);
        }
    }
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        Node* head = new Node;
        _merge(head, list1, list2);

        return head->next;
    }
};